觀前提醒:
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
簡單說,這題的想法,我是在維基百科裡面,關於 Hamming distance 的 Algorithm example ,看到一線曙光。![]()
他在裡面提到下面這段:
It
computes the bitwise exclusive or of the two inputs, and thenfinds the Hamming weight of the result(the number of nonzero bits) using an algorithm of Wegner (1960) that repeatedly finds and clears the lowest-order nonzero bit.
那問題來了,什麼是 Hamming weight(漢明重量) 呢? 他跟我們題目的 Hamming Distance 差別在哪?
殊不知中文版的漢明距離開頭,就提供了非常棒的解答~
- 在資訊理論中,兩個等長字符串之間的漢明距離(英語:Hamming distance)是兩個字符串對應位置的不同字符的個數。換句話說,它就是將一個字符串變換成另外一個字符串所需要替換的字符個數。
漢明重量是字符串相對於同樣長度的零字符串的漢明距離,也就是說,它是字符串中非零的元素個數:對於二進位字符串來說,就是1的個數,所以11101的漢明重量是4。
綜上所述,只需採取以下兩步驟即可求解
/**
* @param {number} x
* @param {number} y
* @return {number}
*/
var hammingDistance = function (x, y) {
let arrOfXXorY = (x ^ y).toString(2).split("");
let hamDis = 0;
for (i = 0; i < arrOfXXorY.length; i++) {
if (arrOfXXorY[i] === "1") {
hamDis++;
}
}
return hamDis;
};
我只能說,遇到 CS 領域中的基礎理論題目,維基百科真的是大家的好朋友![]()
謝謝大家的收看,LeetCode 小學堂我們下次見~![]()